package com.cuit.dashboard.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.dashboard.common.util.Result;
import com.cuit.dashboard.system.dao.SysAdminTokenDao;
import com.cuit.dashboard.system.entity.SysAdminTokenEntity;
import com.cuit.dashboard.system.oauth2.TokenGenerator;
import com.cuit.dashboard.system.service.SysAdminTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @program: zuke
 * @description:
 * @author: KamTang
 * @create: 2022-04-01 19:43
 **/
@Service
public class SysAdminTokenServiceImpl extends ServiceImpl<SysAdminTokenDao, SysAdminTokenEntity> implements SysAdminTokenService {


    /**
     * EXPIRE 过期时间为12小时
     */
    private final static int EXPIRE = 3600 * 12;

    /**
     * 获取token
     *
     * @param userId
     * @return
     */
    @Override
    public Result createToken(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        SysAdminTokenEntity tokenEntity = this.getById(userId);
        if(tokenEntity == null){
            tokenEntity = new SysAdminTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            this.save(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }
        return Objects.requireNonNull(Result.ok().put("token", token)).put("expire", EXPIRE);
    }


    /**
     * 根据令牌获取令牌——验证数据库中是否存在该令牌
     *
     * @param token 令牌
     * @return token
     */
    @Override
    public SysAdminTokenEntity queryByToken(String token) {
        return this.baseMapper.queryByToken(token);
    }

    /**
     * 退出
     *
     * @param id id
     */
    @Override
    public void logout(long id) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        SysAdminTokenEntity tokenEntity = new SysAdminTokenEntity();
        tokenEntity.setUserId(id);
        tokenEntity.setToken(token);
        // 这里虽然是updateById，但是参数可以是实体类
        // 将tokenEntity中的userId和token更新为形参id和新生成的token，其他不变。
        // 如果使用update
        this.baseMapper.updateById(tokenEntity);
    }
}
